/*************************************************************************
 * File Name:    Add_Two_Numbers.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: 2013/11/6 22:03:55
 * 
 * Description:  
 |------------------------------------------------------------------------
 | Problem: Add Two Numbers
 |
 | You are given two linked lists representing two non-negative numbers.
 | The digits are stored in reverse order and each of their nodes contain
 | a single digit. Add the two numbers and return it as a linked list.
 |
 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
 | Output: 7 -> 0 -> 8
 |------------------------------------------------------------------------
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>

using namespace std;

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
    {
        ListNode *ans, *tail;
        ListNode *p1, *p2;
        
        ans = tail = NULL;
        int carry = 0;
        for (p1 = l1, p2 = l2; p1 != NULL && p2 != NULL; p1 = p1->next, p2 = p2->next) {
            if (tail == NULL) {
                ans = tail = new ListNode(p1->val + p2->val);
            } else {
                tail->next = new ListNode(p1->val + p2->val + carry);
                tail = tail->next;
            }
            carry = tail->val / 10;
            tail->val = tail->val % 10;
        }
        
        while (p1 != NULL) {
            tail->next = new ListNode(p1->val + carry);
            tail = tail->next;
            p1 = p1->next;
            carry = tail->val / 10;
            tail->val %= 10;
        }
        
        while (p2 != NULL) {
            tail->next = new ListNode(p2->val + carry);
            tail = tail->next;
            p2 = p2->next;
            carry = tail->val / 10;
            tail->val %= 10;
        }
        
        if (carry > 0) {
            tail->next = new ListNode(carry);
            tail = tail->next;
        }
        if (tail != NULL) tail->next = NULL;
        return ans;
    }
};
